package com.yuandengta.yomall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;
import com.yuandengta.yomall.product.dao.CategoryDao;
import com.yuandengta.yomall.product.entity.CategoryEntity;
import com.yuandengta.yomall.product.service.CategoryService;
import com.yuandengta.yomall.product.vo.Catalog2VO;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CategoryEntity::getShowStatus, "1");

        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /*
     * */
    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装分类父子树形结构
        List<CategoryEntity> level1Category = categoryEntities.stream()
                //查询一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                //递归查找一级分类所有子分类
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity,
                            categoryEntities));
                    return categoryEntity;
                })
                //排序
                .sorted((categoryEntity1, categoryEntity2) -> {
                    return (categoryEntity1.getSort() == null ? 0 :
                            categoryEntity1.getSort()) -
                            (categoryEntity2.getSort() == null ? 0 :
                                    categoryEntity2.getSort());
                })
                .collect(Collectors.toList());

        return level1Category;
    }

    /**
     * 递归查找所有分类的子分类
     *
     * @param root 当前一级分类 * @param all 所有分类
     * @return
     */

    private List<CategoryEntity> getChildren(CategoryEntity root,
                                             List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity ->
                        categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    //递归找子分类 getChildren
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((categoryEntity1, categoryEntity2) -> {
                    //排序
                    return (categoryEntity1.getSort() == null ? 0 :
                            categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 :
                            categoryEntity2.getSort());
                })

                .collect(Collectors.toList());

        return children;
    }

    @Override
    public void delCategory(Long[] catIds) {
        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CategoryEntity::getCatId, Arrays.asList(catIds));

        List<CategoryEntity> list = list(queryWrapper);

        List<CategoryEntity> uplist = list.stream()
                .map(categoryEntity -> {
                    categoryEntity.setShowStatus(0);
                    return categoryEntity;
                })
                .collect(Collectors.toList());

        updateBatchById(uplist);

//        List<Long> id = list.stream()
//                .map(categoryEntity -> {
//                    return categoryEntity.getCatId();
//                })
//                .collect(Collectors.toList());
//
//        for (CategoryEntity entity : list) {
//            entity.setShowStatus(0);
//            updateById(entity);
//        }
    }

    /**
     * 查找三级分类的完整路径
     *
     * @param catelogId 三级分类id
     * @return 三级分类的完整路径
     */

    @Override
    public Long[] findCategoryPath(Long catelogId) {
        if (catelogId == null) {
            return null;
        }
        List<Long> paths = new ArrayList();
        List<Long> fullPath = findParentPath(catelogId, paths);
        //集合数据进行逆序
        Collections.reverse(fullPath);
        return fullPath.toArray(new Long[fullPath.size()]);
    }


    /**
     * 递归收集三级分类的父id
     *
     * @param catelogId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
//        收集当前节点id
        paths.add(catelogId);
//        查询当前分类的信息
        CategoryEntity categoryEntity = getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
//            递归
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    @Override
    public List<CategoryEntity> getLevelCategories() {
        List<CategoryEntity> entities = list(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0)
        );
        return entities;
    }

    /**
     * 查询首页展示分类列表
     * 目前只有二级，，多级的可以写一个递归了。
     * @return
     */
    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson() {
        List<CategoryEntity> categories = getLevelCategories();
        Map<String, List<Catalog2VO>> map = categories.stream().collect(
                Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    List<CategoryEntity> level1Category = list(
                            new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId())
                    );
                    List<Catalog2VO> catalog1VOS = null;
                    if (level1Category != null) {
                        catalog1VOS = level1Category.stream().map(categoryEntity -> {
                            Catalog2VO catalog1VO = new Catalog2VO();

                            catalog1VO.setId(categoryEntity.getCatId().toString());
                            catalog1VO.setParentCid(v.getCatId().toString());
                            catalog1VO.setIcon(categoryEntity.getIcon());
                            catalog1VO.setName(v.getName());

                            List<CategoryEntity> level2Category = list(
                                    new QueryWrapper<CategoryEntity>().eq("parent_cid", categoryEntity.getCatId())
                            );

                            List<Catalog2VO> catalog2VOS = null;
                            if (level2Category != null) {
                                catalog2VOS = level2Category.stream().map(category2Entity -> {
                                    Catalog2VO catalog2VO = new Catalog2VO();

                                    catalog2VO.setId(categoryEntity.getCatId().toString());
                                    catalog2VO.setParentCid(v.getCatId().toString());
                                    catalog2VO.setIcon(categoryEntity.getIcon());
                                    catalog2VO.setName(v.getName());
                                    return catalog2VO;
                                }).collect(Collectors.toList());

                                catalog1VO.setChildren(catalog2VOS);
                            }
                            return catalog1VO;
                        }).collect(Collectors.toList());
                    }
                    return catalog1VOS;
                })

        );
        return map;
    }

}
